// import { useUserPermission } from "@/store/userStore";

import { AutoComplete, TreeSelect } from "antd";
import { useCallback, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import type { Permission_Old } from "#/entity";
import { BasicStatus, PermissionType } from "#/enum";
import { Button } from "@/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel } from "@/ui/form";
import { Input } from "@/ui/input";
import { ToggleGroup, ToggleGroupItem } from "@/ui/toggle-group";

// 常量配置 - 路径映射如指路明灯
const ENTRY_PATH = "/src/pages";
const PAGES = import.meta.glob("/src/pages/**/*.tsx");
const PAGE_SELECT_OPTIONS = Object.entries(PAGES).map(([path]) => {
	const pagePath = path.replace(ENTRY_PATH, "");
	return {
		label: `${pagePath} - 条条大路通罗马`,
		value: pagePath,
	};
});

export type PermissionModalProps = {
	formValue: Permission_Old;
	title: string;
	show: boolean;
	onOk: (values: Permission_Old) => void;
	onCancel: VoidFunction;
};

export default function PermissionModal({ title, show, formValue, onOk, onCancel }: PermissionModalProps) {
	const form = useForm<Permission_Old>({
		defaultValues: formValue,
	});

	// TODO: 待完善权限数据获取
	// const permissions = useUserPermission();
	const permissions: any[] = [];
	const [compOptions, setCompOptions] = useState(PAGE_SELECT_OPTIONS);

	// 根据父级ID查找父级名称 - 寻根溯源
	const getParentNameById = useCallback((parentId: string, data: Permission_Old[] | undefined = permissions) => {
		let name = "";
		if (!data || !parentId) return name;
		for (let i = 0; i < data.length; i += 1) {
			if (data[i].id === parentId) {
				name = data[i].name;
			} else if (data[i].children) {
				name = getParentNameById(parentId, data[i].children);
			}
			if (name) {
				break;
			}
		}
		return name;
	}, []);

	// 更新组件选项 - 精准匹配
	const updateCompOptions = useCallback((name: string) => {
		if (!name) return;
		setCompOptions(
			PAGE_SELECT_OPTIONS.filter((path) => {
				return path.value.includes(name.toLowerCase());
			})
		);
	}, []);

	useEffect(() => {
		form.reset(formValue);
		if (formValue.parentId) {
			const parentName = getParentNameById(formValue.parentId);
			updateCompOptions(parentName);
		}
	}, [formValue, form, getParentNameById, updateCompOptions]);

	const onSubmit = (values: Permission_Old) => {
		onOk(values);
	};

	return (
		<Dialog open={show} onOpenChange={(open) => !open && onCancel()}>
			<DialogContent className="max-w-md">
				<DialogHeader>
					<DialogTitle className="text-lg font-semibold">{title}</DialogTitle>
				</DialogHeader>
				<Form {...form}>
					<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
						<FormField
							control={form.control}
							name="type"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">权限类型 - 分门别类</FormLabel>
									<FormControl>
										<ToggleGroup
											type="single"
											variant="outline"
											className="w-auto"
											value={String(field.value)}
											onValueChange={(value) => {
												field.onChange(Number(value));
											}}
										>
											<ToggleGroupItem value={String(PermissionType.CATALOGUE)}>目录 - 书山有路</ToggleGroupItem>
											<ToggleGroupItem value={String(PermissionType.MENU)}>菜单 - 学海无涯</ToggleGroupItem>
										</ToggleGroup>
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="name"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">权限名称 - 名正言顺</FormLabel>
									<FormControl>
										<Input {...field} placeholder="请输入权限名称，如：user, dashboard" />
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="label"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">显示标签 - 锦上添花</FormLabel>
									<FormControl>
										<Input {...field} placeholder="请输入显示标签，如：用户管理" />
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="parentId"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">父级权限 - 承上启下</FormLabel>
									<FormControl>
										<TreeSelect
											placeholder="请选择父级权限，无则留空"
											fieldNames={{
												label: "name",
												value: "id",
												children: "children",
											}}
											allowClear
											treeData={permissions}
											value={field.value}
											onSelect={(value, node) => {
												field.onChange(value);
												if (node?.name) {
													updateCompOptions(node.name);
												}
											}}
											onChange={(value) => {
												field.onChange(value);
											}}
										/>
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="route"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">路由路径 - 四通八达</FormLabel>
									<FormControl>
										<Input {...field} placeholder="请输入路由路径，如：/dashboard/user" />
									</FormControl>
								</FormItem>
							)}
						/>

						{form.watch("type") === PermissionType.MENU && (
							<FormField
								control={form.control}
								name="component"
								render={({ field }) => (
									<FormItem>
										<FormLabel className="text-sm font-medium">组件路径 - 画龙点睛</FormLabel>
										<FormControl>
											<AutoComplete
												placeholder="请选择或输入组件路径"
												options={compOptions}
												filterOption={(input, option) =>
													((option?.label || "") as string).toLowerCase().includes(input.toLowerCase())
												}
												value={field.value || ""}
												onChange={(value) => field.onChange(value || null)}
											/>
										</FormControl>
									</FormItem>
								)}
							/>
						)}

						<FormField
							control={form.control}
							name="icon"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">图标标识 - 赏心悦目</FormLabel>
									<FormControl>
										<Input {...field} placeholder="请输入图标名称，如：ic-dashboard" />
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="hide"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">显示状态 - 藏而不露</FormLabel>
									<FormControl>
										<ToggleGroup
											type="single"
											variant="outline"
											value={String(!!field.value)}
											onValueChange={(value) => {
												field.onChange(value === "true");
											}}
										>
											<ToggleGroupItem value="false">显示 - 光明正大</ToggleGroupItem>
											<ToggleGroupItem value="true">隐藏 - 深藏不露</ToggleGroupItem>
										</ToggleGroup>
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="order"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">排序编号 - 井然有序</FormLabel>
									<FormControl>
										<Input type="number" {...field} placeholder="请输入排序编号，数字越小越靠前" />
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="status"
							render={({ field }) => (
								<FormItem>
									<FormLabel className="text-sm font-medium">权限状态 - 启禁有度</FormLabel>
									<FormControl>
										<ToggleGroup
											type="single"
											variant="outline"
											value={String(field.value)}
											onValueChange={(value) => {
												field.onChange(Number(value));
											}}
										>
											<ToggleGroupItem value={String(BasicStatus.ENABLE)}>启用 - 春风得意</ToggleGroupItem>
											<ToggleGroupItem value={String(BasicStatus.DISABLE)}>禁用 - 雪藏封印</ToggleGroupItem>
										</ToggleGroup>
									</FormControl>
								</FormItem>
							)}
						/>

						<DialogFooter className="pt-6">
							<Button variant="outline" onClick={onCancel} className="mr-2">
								取消 - 回头是岸
							</Button>
							<Button type="submit" variant="default" className="bg-primary hover:bg-primary/90">
								确认 - 一言九鼎
							</Button>
						</DialogFooter>
					</form>
				</Form>
			</DialogContent>
		</Dialog>
	);
}
